package com.itheima.reggie.controller;


import com.itheima.reggie.common.R;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    //根目录配置在springboot的yml配置文件中,方便管理
    @Value("${reggie.path}")
    private String reggiePath;

    /**
     * @param file spring框架提供的
     */
    //图片上传
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        //生成随机图片名称
        String pictureName = UUID.randomUUID().toString();
        //原始文件名
        String originalFilename = file.getOriginalFilename();
        //获取图片格式(.jpg/.png....)
        String pictureFormat = originalFilename.substring(originalFilename.lastIndexOf("."));
        log.info("图片格式:{}", pictureFormat);
        //根目录reggiPath不存在就创建一个
        File dir = new File(reggiePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //file是一个临时文件,需要转存到指定位置
        try {
            file.transferTo(new File(reggiePath + pictureName + pictureFormat));
            log.info("图片全路径:{}", reggiePath + pictureName + pictureFormat);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //返回文件名称
        return R.success(pictureName + pictureFormat);
    }

    //图片下载
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        try {
            //输入流,通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(reggiePath + name);
            //输出流,通过输出流将文件写回浏览器,在浏览器展示图片
            response.setContentType("image/jpeg");
            ServletOutputStream outputStream = response.getOutputStream();
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            //关闭资源
            fileInputStream.close();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
